package com.designmodel.proxymodel.dynamicproxy.jdkdynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by
 *
 * @author touni
 * @date 2019/4/1
 * @time 12:54
 */
public class DynamicProxy {
    private Object object;


    public DynamicProxy(){}
    public DynamicProxy(Object object){
        this.object = object;
    }  //通过构造方法传入代理的对象

    public Object createProxy(){
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //编写业务需求
                        Object obj;
                        if (method.getName().equalsIgnoreCase("click")){
                            System.out.println("点击方法即将执行");
                            obj = method.invoke(object, args);   //代理对象需要传入 和cglib不同  和方法的参数
                            System.out.println("点击方法运行结束");
                            return obj;
                        }
                        System.out.println("非点击方法即将运行");
                        obj = method.invoke(object, args);
                        System.out.println("非点击方法运行结束");
                        return obj;
                    }
                });


    }

}
